define(['jquery', 'bootstrap', 'webuploader', 'aojie', 'template'], function ($, undefined, WebUploader, Aojie, template) {
    var Upload = {
        list: {},
        config: {
            //容器
            container: document.body,
            //类名
            class_name: '.webupload:not([initialized])',
            //预览图
            preview_tpl: '<li class="col-xs-4 col-sm-3 col-md-2 file-item" data-url="{{url}}"><figure><img src="{{src}}" onerror="this.src=\'' + Aojie.api.fixurl("/admin/ajax/icon") + '?suffix=\'+\'{{url}}\'.split(\'.\').pop();this.onerror=null;" alt=""><figcaption><a class="btn btn-round btn-square btn-primary btn-enlarge-file" href="#!"><i class="fa fa-eye"></i></a><a class="btn btn-round btn-square btn-danger btn-trash-file" href="#!"><i class="fa fa-trash"></i></a></figcaption></figure></li>',
            //基础路径
            base_url: "/public/static/backend/libs/fex-webuploader/dist",
        },
        events: {
            //文件加入队列之前出发
            beforeFileQueued: function (file, input_id, preview_id) {
                // console.log('文件加入之前事件');
                // console.log(file);
                // console.log('----------end---------------');
            },
            fileQueued: function (file, input_id, preview_id, uploader) {
                //
            },
            fileDequeued: function (file, input_id, preview_id, uploader) {
                console.log('文件删除后');
                console.log(file);
                console.log('----------end---------------');
            },
            uploadFinished: function (file, input_id, preview_id, uploader) {
                console.log('当所有文件上传结束时触发。');
                console.log(file);
                console.log('----------end---------------');
            },
            uploadError: function (file, response, input_id, preview_id, uploader) {
                Toastr.error(response.msg);
                return false;
            },
            uploadSuccess: function (file, response, input_id, preview_id, uploader) {
                if (response.code == 1) {
                    var input_obj = $("#" + input_id);
                    var input_value = input_obj.val();
                    var multiple = uploader.options.pick.multiple;
                    var data = {suffix: file.ext, url: response.data.save_name, src: response.data.save_name};
                    uploader.makeThumb(file, function (error, src) {
                        if (error) {
                            data.src = '';//如果无法创建 则代表不是图片类型文件
                        }
                        if (multiple) {
                            var html = template.render(Upload.config.preview_tpl, data);//多选则重新追加图片预览
                            $("#" + preview_id).append(html);
                        } else {
                            var html = template.render(Upload.config.preview_tpl, data);//多选则重新追加图片预览
                            $("#" + preview_id).empty().append(html);
                        }
                    }, 146, 146);

                    if (multiple) {
                        //最终赋值
                        input_value = input_value == '' ? [] : input_value.split(',');
                        input_value.push(response.data.save_name);
                    } else {
                        input_value = response.data.save_name;
                    }
                    input_obj.val(input_value);
                } else {
                    this.uploadError(file, response, input_id, preview_id, uploader)
                }
            },
            uploadComplete: function (file, input_id, preview_id, uploader) {

            },
            error: function (type, input_id, preview_id, uploader) {
                console.log(uploader);
                var msg = '网络异常';
                switch (type) {
                    case 'F_EXCEED_SIZE':
                    case 'Q_EXCEED_SIZE_LIMIT':
                        msg = '文件大小超出最大限制:' + uploader.options.max_size;
                        break;
                    case 'Q_TYPE_DENIED':
                        msg = '仅允许上传 ' + uploader.options.accept.extensions + ' 格式的文件，请重新选择'
                        break;
                    case 'Q_EXCEED_NUM_LIMIT':
                        msg = '超过文件上传数量'
                        break;
                }
                Toastr.error(msg);
                return false;
            }
        },
        default: {
            dnd: undefined,
            disableGlobalDnd: false,
            paste: undefined,
            pick: {
                id: '',
                innerHTML: '请选择文件',
                multiple: false,
            },
            accept: {
                title: '允许上传类型',
                extensions: '',
                mimeTypes: '',
            },
            max_size: '',
        },
        api: {
            webuploader: function (element) {
                element = typeof element === 'undefined' ? Upload.config.class_name : element;
                $(element, Upload.config.container).each(function () {
                    if ($(this).attr("initialized")) {
                        return true;
                    }
                    $(this).attr("initialized", true);
                    var that = this;
                    var id = $(this).prop("id");
                    var url = $(this).data("url");
                    var maxsize = $(this).data("maxsize");
                    var mimetype = $(this).data("mimetype");
                    var multiple = $(this).data("multiple");
                    var extensions = $(this).data("extensions");
                    var formData = $(this).data('formdata');
                    //填充ID
                    var input_id = $(that).data("input-id") ? $(that).data("input-id") : "";
                    //预览ID
                    var preview_id = $(that).data("preview-id") ? $(that).data("preview-id") : "";
                    //上传URL
                    url = url ? url : Config.upload.uploadurl;
                    url = Aojie.api.fixurl(url);
                    //最大可上传文件大小
                    maxsize = typeof maxsize !== "undefined" ? maxsize : Config.upload.maxsize;
                    var msg_max_size = maxsize;
                    var arr = maxsize.match(/(\d+)|(\w+)/g);
                    if (arr.length == 2) {
                        var num = arr[0].toLowerCase();
                        var unit = arr[1].toLowerCase();
                        var type_dict = {'b': 0, 'k': 1, 'kb': 1, 'm': 2, 'mb': 2, 'gb': 3, 'g': 3};
                        var powY = type_dict[unit];
                        powY = typeof powY !== 'undefined' ? powY : 0
                        maxsize = parseInt(maxsize) * Math.pow(1024, powY);
                    }
                    //文件类型
                    mimetype = typeof mimetype !== "undefined" ? mimetype : Config.upload.mimetype;
                    //是否支持批量上传
                    multiple = typeof multiple !== "undefined" ? multiple : Config.upload.multiple;
                    formData = typeof formData !== "undefined" ? formData : undefined;

                    var innerHtml = $(this).text();
                    innerHtml = typeof innerHtml !== "undefined" ? innerHtml : '上传';
                    var obj = {
                        pick: {
                            id: that,
                            innerHTML: innerHtml,
                            multiple: multiple
                        },
                        accept: {
                            title: '允许上传类型',
                            extensions: extensions,
                            mimeTypes: mimetype,
                        },
                        auto: true,
                        // swf文件路径
                        swf: Upload.config.base_url + '/Uploader.swf',
                        formData: formData,
                        disableGlobalDnd: true,
                        chunked: false,
                        duplicate: true,
                        server: url,
                        fileSizeLimit: undefined,
                        fileSingleSizeLimit: maxsize,   // N M
                        max_size: msg_max_size,
                    }
                    obj = $.extend(Upload.default, obj)
                    Upload.list[id] = WebUploader.create(obj);
                    Upload.list[id].onBeforeFileQueued = function (file) {
                        Upload.events.beforeFileQueued(file, input_id, preview_id, Upload.list[id]);
                    };
                    Upload.list[id].onFileQueued = function (file) {
                        Upload.events.fileQueued(file, input_id, preview_id, Upload.list[id]);
                    };
                    // Upload.list[id].onFilesQueued = function (file) {
                    //     Upload.events.filesQueued(file);
                    // };
                    // Upload.list[id].onFileDequeued = function (file) {
                    //     Upload.events.fileDequeued(file);
                    // };
                    Upload.list[id].onUploadFinished = function (file) {
                        Upload.events.uploadFinished(file, input_id, preview_id, Upload.list[id]);
                    };
                    Upload.list[id].onUploadError = function (file) {
                        Upload.events.uploadError(file, input_id, preview_id, Upload.list[id]);
                    };
                    Upload.list[id].onUploadSuccess = function (file, response) {
                        Upload.events.uploadSuccess(file, response, input_id, preview_id, Upload.list[id]);
                    };
                    Upload.list[id].onUploadComplete = function (file) {
                        Upload.events.uploadComplete(file, input_id, preview_id, Upload.list[id]);
                    };
                    Upload.list[id].onError = function (file) {
                        Upload.events.error(file, input_id, preview_id, Upload.list[id]);
                    };

                    if (preview_id) {
                        // 监听事件
                        $(document.body).on("aj.preview.change", "#" + preview_id, function () {
                            var urlArr = [];
                            $("#" + preview_id + " [data-url]").each(function (i, j) {
                                urlArr.push($(this).data("url"));
                            });
                            if (input_id) {
                                $("#" + input_id).val(urlArr.join(","));
                            }
                        });
                    }
                    if (preview_id && multiple) {
                        require(['sortable'], function (Sortable) {
                            var sortable_obj = document.getElementById(preview_id);
                            new Sortable(
                                sortable_obj,
                                {
                                    multiDrag: true,
                                    selectedClass: 'file-item-select',
                                    animation: 150,
                                    onEnd: function (evt) {
                                        $("#" + preview_id).trigger("aj.preview.change");
                                    }
                                }
                            );
                        });
                    }
                    if (input_id && preview_id) {
                        $(document.body).on("keyup change", "#" + input_id, function (e) {
                            var inputStr = $("#" + input_id).val();
                            var inputArr = inputStr.split(/\,/);
                            $("#" + preview_id).empty();
                            //模板
                            var tpl = $("#" + preview_id).data("template") ? $("#" + preview_id).data("template") : "";
                            $.each(inputArr, function (i, j) {
                                if (!j) {
                                    return true;
                                }
                                var data = {
                                    suffix: j.split('.').pop(),
                                    url: j,
                                    src: j
                                };
                                var html = tpl ? template(tpl, data) : template.render(Upload.config.preview_tpl, data);
                                $("#" + preview_id).append(html);
                            });
                        });
                        $("#" + input_id).trigger("change");

                        //删除事件
                        $(document.body).on('click', '.btn-trash-file', function () {
                            var that = $(this).parents('li.file-item');
                            var noshow_content = sessionStorage.getItem('noshow_content');
                            noshow_content = noshow_content == null ? 'true' : 'false';
                            if (noshow_content == 'true') {
                                layer.open({
                                    title: '警告',
                                    content: '<div>确定删除吗?</div><label class="lyear-checkbox checkbox-purple m-t-10"><input type="checkbox"><span>不在提醒</span></label>'
                                    , btn: ['确定', '取消']
                                    , offset: 'auto'
                                    , yes: function (index, layero) {
                                        if ($("#confirm_del").is(':checked')) {
                                            sessionStorage.setItem("noshow_content", 'true');
                                        }
                                        delconfirm(that, preview_id);
                                        layer.close(index);
                                    }
                                });
                            } else {
                                console.log('执行到这里了');
                                delconfirm(that, preview_id);
                            }
                        })
                        //展示大图
                        $(document.body).on('click', '.btn-enlarge-file', function () {
                            var that = $(this).parents('li.file-item');
                            var data = [];
                            value = that.data('url').split(',');
                            $.each(value, function (index, value) {
                                data.push({
                                    src: value
                                });
                            });
                            layer.photos({
                                photos: {
                                    "start": 0,
                                    "data": data
                                },
                                anim: 0 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                            });
                        });
                    }
                });
                var delconfirm = function (that, preview_id) {
                    that.remove();
                    $("#" + preview_id).trigger("aj.preview.change");
                }
            }
        }
    }
    return Upload;
})